<script setup>
import { useCartStore } from '@/stores/cart.js'
import { useRouter } from 'vue-router'
import { getAddressAPI, addAddressAPI, putAddressAPI } from '@/api/address.js'
import { postOrderAPI } from '@/api/order.js'
import { onMounted, ref } from 'vue'
const router = useRouter()
const addressList = ref([])
const activeAddress = ref()
const getAddress = async () => {
  const res = await getAddressAPI()
  addressList.value = res.data.result
  activeAddress.value = addressList.value[0]
}
onMounted(async () => {
  getAddress()
})
//展示的地址
const index = ref(0)
const cartStore = useCartStore()
const deliveryTimeType = ref([
  '不限配送时间：周一至周日',
  '工作日送货：周一至周五',
  '双休日、假日送货：周六至周日'
])
const activeDelivery = ref(0)
const selectDelivery = (index) => {
  activeDelivery.value = index
}
const PayType = ref(['在线支付', '货到付款'])
const activePay = ref(0)
const selectPay = (index) => {
  activePay.value = index
}
//地址相关
const title = ref()
const addressForm = ref({
  receiver: '',
  contact: '',
  provinceCode: '',
  cityCode: '',
  countyCode: '',
  address: '',
  postalCode: '',
  addressTags: '',
  fullLocation: ''
})
const rules = ref({
  receiver: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  contact: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  provinceCode: [
    { required: true, message: '输入框不能为空', trigger: 'blur' }
  ],
  cityCode: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  countyCode: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  postalCode: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  addressTags: [{ required: true, message: '输入框不能为空', trigger: 'blur' }],
  fullLocation: [{ required: true, message: '输入框不能为空', trigger: 'blur' }]
})
const labels = [
  '收货人-姓名',
  '收货人-联系方式',
  '收货人-省份编码',
  '收货人-城市编码',
  '收货人-地区编码',
  '收货人-详细地址',
  '收货人-邮政编码',
  '收货人-地址标签',
  '收货人-完整地址'
]
const isDefault = ref(1) //是否设为默认地址，0是，1不是
const changeDefault = () => {
  isDefault.value = !isDefault.value
}
const isShow = ref(false)
const addAddress = () => {
  isShow.value = true
  title.value = '新增地址'
}
const isChange = ref(false)
const changeAddress = () => {
  isChange.value = true
  title.value = '切换地址'
}
//添加数据的校验并提交
const ruleFormRef = ref()
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = { ...addressForm.value, isDefault: isDefault.value }
      console.log(data)
      if (!isChange.value) {
        ElMessage.success('新增成功！')

        await addAddressAPI(data)
      } else {
        ElMessage.success('修改成功！')
        let id = addressForm.value.id
        await putAddressAPI(id, data)
      }
      getAddress()
      isShow.value = false
      formEl.resetFields()
    } else {
      console.log('error submit!', fields)
    }
  })
}
//修改的地址时选择的地址

const selectAddress = ref(0)
let time = null
const handleselectAddress = (index) => {
  clearTimeout(time)
  time = setTimeout(() => {
    selectAddress.value = index
  }, 300)
}
const confirmAddress = (i) => {
  clearTimeout(time)
  selectAddress.value = i
  index.value = selectAddress.value
  activeAddress.value = addressList.value[i]
  isChange.value = false
}
//提交订单
const submitOrder = async () => {
  let obj = {}
  obj.deliveryTimeType = activeDelivery.value + 1
  obj.payType = activePay.value + 1
  obj.payChannel = 1
  obj.buyerMessage = ''
  obj.goods = cartStore.cartList.map((item) => {
    return {
      skuId: item.skuId,
      count: item.count
    }
  })
  obj.addressId = activeAddress.value.id
  console.log(obj)
  const res = await postOrderAPI(obj)
  const id = res.data.result.id
  cartStore.deleteAll()
  router.push(`/pay/${id}`)
}
const editAddress = (item) => {
  addressForm.value = item
  isShow.value = true
}
</script>
<template>
  <div class="pay">
    <h3>收货地址</h3>
    <el-row>
      <el-col :span="16">
        <p>
          收货人：<span>{{ addressList[index]?.receiver }}</span>
        </p>
        <p>
          联系方式：<span>{{ addressList[index]?.contact }}</span>
        </p>
        <p>
          收货地址：<span>{{ addressList[index]?.address }}</span
          ><span>{{ addressList[index]?.fullLocation }}</span>
        </p></el-col
      >
      <el-col :span="8" class="btn">
        <el-button @click="changeAddress">切换地址</el-button>
        <el-button @click="addAddress">新增地址</el-button></el-col
      >
      <el-dialog v-model="isChange" :title="title" center class="dialog">
        <div
          class="changeAddresses"
          v-for="(item, index) in addressList"
          :key="item"
          :class="{ activeSelectAddress: index === selectAddress }"
          @click="handleselectAddress(index)"
          @dblclick="confirmAddress(index)"
        >
          <div>
            <p>
              收货人：<span>{{ item?.receiver }}</span>
            </p>
            <p>
              联系方式：<span>{{ item?.contact }}</span>
            </p>
            <p>
              收货地址：<span>{{ item?.address }}</span
              ><span>{{ item?.fullLocation }}</span>
            </p>
          </div>
          <el-button @click="editAddress(item)">编辑地址</el-button>
        </div>
      </el-dialog>
      <!-- 新增地址 -->
      <el-dialog
        v-model="isShow"
        :title="title"
        center
        destroy-on-close
        class="dialog"
      >
        <el-form
          :model="addressForm"
          class="form"
          status-icon
          :rules="rules"
          ref="ruleFormRef"
        >
          <el-form-item :label="labels[0]" prop="receiver"
            ><el-input
              v-model="addressForm.receiver"
              :placeholder="`请输入${labels[0]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[1]" prop="contact"
            ><el-input
              v-model="addressForm.contact"
              :placeholder="`请输入${labels[1]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[2]" prop="provinceCode"
            ><el-input
              v-model="addressForm.provinceCode"
              :placeholder="`请输入${labels[2]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[3]" prop="cityCode"
            ><el-input
              v-model="addressForm.cityCode"
              :placeholder="`请输入${labels[3]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[4]" prop="countyCode"
            ><el-input
              v-model="addressForm.countyCode"
              :placeholder="`请输入${labels[4]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[5]" prop="address"
            ><el-input
              v-model="addressForm.address"
              :placeholder="`请输入${labels[5]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[6]" prop="postalCode"
            ><el-input
              v-model="addressForm.postalCode"
              :placeholder="`请输入${labels[6]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[7]" prop="addressTags"
            ><el-input
              v-model="addressForm.addressTags"
              :placeholder="`请输入${labels[7]}`"
            ></el-input
          ></el-form-item>
          <el-form-item :label="labels[8]" prop="fullLocation"
            ><el-input
              v-model="addressForm.fullLocation"
              :placeholder="`请输入${labels[8]}`"
            ></el-input
          ></el-form-item>
          <div class="address-btn">
            <el-check-tag :checked="isDefault" @change="changeDefault"
              >是否设为默认地址</el-check-tag
            >
            <el-button type="success" @click="submitForm(ruleFormRef)"
              >提交</el-button
            >
          </div>
        </el-form></el-dialog
      >
    </el-row>
    <!-- 商品详情 -->
    <h3>商品信息</h3>
    <el-table
      ref="multipleTableRef"
      :data="cartStore.cartList.filter((i) => i.selected)"
      style="width: 100%"
    >
      <el-table-column width="60"
        ><template #default="scope"
          ><img
            style="width: 50px; height: 50px"
            :src="cartStore.cartList[scope.$index].picture"
            alt="" /></template
      ></el-table-column>
      <el-table-column prop="name" label="商品信息" width="300" />
      <el-table-column prop="price" label="单价" width="200" />
      <el-table-column prop="count" label="数量" width="200" />
      <el-table-column prop="totalPrice" label="小计" width="200" />
      <el-table-column prop="totalPrice" label="实付" />
    </el-table>
    <h3>配送时间</h3>
    <el-tag
      v-for="(item, index) in deliveryTimeType"
      :key="item"
      :type="primary"
      class="delivery"
      effect="plain"
      size="large"
      @click="selectDelivery(index)"
      :class="{ active: index === activeDelivery }"
    >
      {{ item }}
    </el-tag>
    <h3>支付方式</h3>
    <el-tag
      v-for="(item, index) in PayType"
      :key="item"
      :type="primary"
      class="delivery"
      effect="plain"
      size="large"
      @click="selectPay(index)"
      :class="{ active: index === activePay }"
    >
      {{ item }}
    </el-tag>
    <h3>金额明细</h3>
    <el-row :justify="end">
      <el-col :offset="18" :span="6" class="moneyDetail">
        <p>
          商品件数：<span>{{ cartStore.totalNum }}</span>
        </p>
        <p>
          商品总价：<span>{{ cartStore.totalPrice }}</span>
        </p>
        <p>运费：<span>12</span></p>
        <p class="lastMoney">
          应付金额：<span>{{ cartStore.totalPrice + 12 }}</span>
        </p></el-col
      >
    </el-row>
    <h3 />
    <div class="submit">
      <el-button type="success" size="large" @click="submitOrder"
        >提交订单</el-button
      >
    </div>
  </div>
</template>
<style scoped lang="scss">
.pay {
  background-color: #f8f4ed;
  padding: 1% 2%;
  :deep(.el-dialog--center .el-dialog__body) {
    height: 60vh !important;
    overflow: auto !important;
  }
  .lastMoney {
    font-size: 20px !important;
    span {
      color: red;
    }
  }
  .changeAddresses {
    overflow: auto;
    background-color: #f8f4ed;
    padding: 1% 2%;
    margin: 2% 10%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .activeSelectAddress {
    border: 2px solid #ef3473;
  }

  .address-btn {
    display: flex;
    justify-content: space-between;
    margin: 5px;
  }
  .form {
    .active {
      border: 2px solid #ef3473;
    }
  }

  .moneyDetail {
    width: 100%;
  }
  & > h3 {
    font-family: 像素字体;
    border-bottom: 1px solid grey;
    margin-bottom: 2%;
  }
  & > div {
    margin-left: 1%;
    & > div:first-child {
      p {
        font-size: 16px;
        font-family: 小可奶酪体;
        span {
          margin-right: 3%;
          font-family: 加油鸭;
        }
      }
    }
    .btn {
      font-family: 素材集市;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .el-table {
    --el-table-header-bg-color: #c0c4c3;
  }
  .delivery {
    margin: 2%;
    &.active {
      border: 2px solid #ef3473;
    }
  }
  .submit {
    display: flex;
    justify-content: end;
    width: 90%;
  }
}
</style>
